<template>
    <view class="submit-page">
        <view class="user-info">
            <view class="user-view user-info">
                <!-- <text class="user-text">{{ userInfo.username }}</text> -->
                <!-- <button type="default" size="mini" @tap="logout" style="">退出登录</button> -->
            </view>
        </view>
        <!-- 表单区域 -->
        <form @submit="handleSubmit">
            <view class="form-item">
                <label for="number">上道工序：</label>
                <text>{{ formData.process }}</text>
            </view>

            <!-- 订单号输入框 -->
            <view class="form-item">
                <label for="order-number">单号：</label>
                <text style="color: red">{{ formData.workOrderNumber }}</text>
                <!-- <input class="uni-input" id="order-number" v-model="formData.order_sn" placeholder="请输入订单号" /></input> -->
            </view>
            <scanCode />
            <view class="form-item">
                <label for="number">报工人：</label>
                <text>{{ userInfo.username }}</text>
            </view>
            <view class="form-item">
                <label for="number">工序：</label>
                <text style="color: red">{{ formData.craft }}</text>
            </view>
            <view class="form-item">
                <label for="number">订单米数：</label>
                <text>{{ formData.length }}</text>
            </view>
            <view class="form-item">
                <label for="number">转入工序：</label>
                <text>{{ formData.xg }}</text>
            </view>
            <!-- 状态单选框 -->
            <!-- <view class="form-item">
              <label>状态：</label>
              <radio-group @change="radioChange">
                  <label class="radio label-item" v-for="(option, index) in statusOptions" :key="index">
                      <radio :value="option.value" :checked="option.checked">{{ option.label }}</radio>
                  </label>
              </radio-group>
          </view> -->
            <view>
                <button
                    type="primary"
                    form-type="submit"
                    style="width: 40%; float: left; margin-left: 5%"
                >
                    提交
                </button>
                <button
                    type="primary"
                    form-type="submit"
                    style="width: 40%; margin-right: 5%"
                >
                    取消
                </button>
            </view>
        </form>
    </view>
</template>

<script>
import scanCode from "@/components/lg-scanCode/scanCode.vue";
export default {
    components: {
        scanCode,
    },
    data() {
        return {
            formData: {
                order_sn: "",
                craft: uni.getStorageSync("craft"), //工序
                process: "",
                length: "",
                xg: "",
            },
            statusOptions: [
                {
                    value: "1",
                    label: "上机",
                    checked: true,
                },
                {
                    value: "2",
                    label: "下机",
                },
            ],
            current: 0,
            userInfo: {
                username: uni.getStorageSync("username"),
            },
            id: "",
        };
    },
    onUnload() {
        // 移除监听事件
        uni.$off("PDAScan");
    },
    onLoad: function () {
        // var that = this;
        // //setStorageSync数据存储
        // that.setStorageSyncData()
        let token = uni.getStorageSync("token");
        console.log("t", token);
        if (!token) {
            navigateAfterSuccess("9", "登录失效,请重新登录");
        }
    },
    onShow() {
        let that = this;
        uni.$off("PDAScan"); // 每次进来先 移除全局自定义事件监听器
        uni.$on("PDAScan", (res) => {
            console.log("扫码结果：", res.code);
            this.formData.workOrderNumber = res.code;

            var workOrderNumber = res.code;
            uni.request({
                url:
                    "http://121.40.25.211:8080/qb/task/selectTask?workOrderNumber=" +
                    workOrderNumber,
                method: "GET",
                header: {
                    "content-type": "application/json",
                    Authorization: uni.getStorageSync("token"),
                },
                success: (res) => {
                    let ret = res.data.data;
                    console.log(ret);
                    // 工序流程映射，根据数字值映射工序
                    const processMap = {
                        1: ["裁剪", "复合", "包装", "发货"], // 素布工序
                        2: [
                            "裁剪",
                            "绣花",
                            "绣花质检",
                            "定型",
                            "定型质检",
                            "精裁",
                            "剪线",
                            "复合",
                            "包装",
                            "发货",
                        ], // 绣花工序
                    };

                    // 根据 fabricType 确定工序流程
                    let workflow = processMap[ret.fabricType];

                    this.formData.process = ret.process;
                    this.formData.length = ret.length;
                    this.id = ret.productionTaskId;
                    // 根据当前工序确定下一道工序
                    let currentIndex = workflow.indexOf(this.formData.process);

                    if (
                        currentIndex !== -1 &&
                        currentIndex + 1 < workflow.length
                    ) {
                        this.formData.xg = workflow[currentIndex + 1];
                        this.$set(
                            this.formData,
                            "xg",
                            workflow[currentIndex + 1]
                        );
                        // Vue.set(this.formData, 'xg', workflow[currentIndex + 1]);
                        // this.$forceUpdate()
                    } else {
                        this.formData.xg = "流程结束"; // 如果当前工序是列表中的最后一个或未找到，设为流程结束
                    }

                    console.log("Current Index:", currentIndex);
                    console.log("Next Process:", this.formData.xg);
                },
                fail: function (err) {
                    console.log(err);
                },
            });
        });
    },
    methods: {
        handleSubmit(e) {
            e.preventDefault(); // 阻止默认表单提交行为
            // 提交表单数据到服务器的逻辑...
            console.log("Submitting data:", this.formData);
            try {
                // if (!this.formData.order_sn) {
                // 	showErrorToast('请填写订单号');
                // 	return;
                // }
                if (!uni.getStorageSync("token")) {
                    navigateAfterSuccess("9", "登录失效,请重新登录");
                    return false;
                }
                const fromdata = {
                    length: this.formData.length,
                    worker: this.userInfo.username,
                    productionTaskId: this.id,
                    process: this.formData.xg,
                };
                // console.log(fromdata)
                uni.request({
                    url: "http://121.40.25.211:8080/qb/task/updateProcess",
                    method: "POST",
                    data: fromdata,
                    header: {
                        "content-type": "application/json",
                        Authorization: uni.getStorageSync("token"),
                    },
                    success: (res) => {
                        console.log(res.data);
                        let ret = res.data;
                        if (ret.code == 0) {
                            navigateAfterSuccess();
                        } else {
                            showErrorToast(ret.msg);
                            return false;
                        }
                    },
                    fail: function (err) {
                        console.log(err);
                    },
                });
                this.formData.order_sn = "";
                this.formData.status = "1";
            } catch (error) {
                // 处理登录失败逻辑，例如显示错误信息
                console.error("api failed:", error);
            }
        },
        logout() {
            // 实现退出登录逻辑，可能包括清除本地存储的 token、向服务器发送登出请求等
            console.log("Logging out");
            try {
                uni.request({
                    url: "/api/api.php",
                    method: "POST",
                    data: {
                        mode: "login_out",
                    },
                    header: {
                        "content-type": "application/x-www-form-urlencoded",
                        token: uni.getStorageSync("token"),
                    },
                    success(res) {
                        console.log(res);
                        let ret = res.data;
                        if (ret.code == 0) {
                            uni.removeStorageSync("token");
                            uni.removeStorageSync("craft"); //工序
                            uni.removeStorageSync("username");
                            navigateAfterSuccess("loginout", "重新登录");
                        } else {
                            showErrorToast(ret.msg);
                            return false;
                        }
                    },
                    fail: function (err) {
                        console.log(err);
                    },
                });
            } catch (error) {
                // 处理登录失败逻辑，例如显示错误信息
                console.error("api failed:", error);
            }
            // 更新用户状态（此处仅做演示，实际应修改全局状态或使用 Vuex）
            this.userInfo.username = null;
        },
        radioChange: function (evt) {
            for (let i = 0; i < this.statusOptions.length; i++) {
                if (this.statusOptions[i].value === evt.detail.value) {
                    this.current = i;
                    this.formData.status = evt.detail.value;
                    break;
                }
            }
        },
    },
};

function showErrorToast(message) {
    uni.showToast({
        icon: "none",
        title: message,
    });
}

function navigateAfterSuccess(flag = "", tmpmsg = "操作成功") {
    // 显示登录成功提示
    uni.showToast({
        title: tmpmsg,
        icon: "success",
        duration: 1000, // 自定义持续时间
    });
    if (flag == "") {
        return 0;
    }
    // 使用 Promise 链接，等待提示消失后跳转
    new Promise((resolve) => setTimeout(resolve, 1500)).then(() => {
        uni.navigateTo({
            url: "/pages/index/login",
        });
    });
}
</script>

<style scoped>
.submit-page {
    position: relative;
    margin-top: 15px;
    /* height: 100%; */
}

.header-right {
    /* position: fixed;
    top: 47px;
    right: 20px;
    z-index: 999; */
}

.user-info {
    display: flex;
    justify-content: center;
    /* 水平居中子元素 */
    align-items: center;
    gap: 8px;
}

.user-view {
    margin-left: auto;
    padding-top: 4px;
    padding-right: 7px;
}

.user-text {
    /* 文本相关样式 */
    padding-right: 20px;
}

.my-button {
    /* 按钮相关样式 */
}

.form-item {
    margin-bottom: 16px;
    margin-left: 5px;
}

.label-item {
    margin-right: 16px;
}

.uni-input {
    width: 100%;
    height: 40px;
    font-size: 16px;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 0 10px;
}
</style>
